package com.sskj.hangqing.ui.fragment;


import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.hangqing.R;
import com.sskj.hangqing.R2;
import com.sskj.hangqing.bean.rxbus.QuBean;
import com.sskj.hangqing.presenter.CoinFragmentPresenter;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.CoinEnum;
import com.sskj.lib.bean.CoinType;
import com.sskj.lib.bean.ColorEnum;
import com.sskj.lib.util.CoinUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.APP_FRAGMENT_COIN_LIST)
public class CoinListFragment extends BaseFragment<CoinFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.tvUSDT)
    TextView tvUSDT;
    @BindView(R2.id.tvETH)
    TextView tvETH;
    @BindView(R2.id.tvBTC)
    TextView tvBTC;
    @BindView(R2.id.llTop)
    LinearLayout llTop;
    private SlimAdapter<CoinBean> slimAdapter;
    private Map<String, Disposable> timeMap = new HashMap<>();
    @Autowired
    boolean isSlide = false;
    private HashMap<String, String> coinMap;
    @Autowired
    String qu = "USDT";

    @Override
    protected int getLayoutId() {
        return R.layout.app_fragment_coin;
    }

    @Override
    public CoinFragmentPresenter getPresenter() {
        return new CoinFragmentPresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        ARouter.getInstance().inject(this);
        if (qu.equals(Constans.DANWEI)) {
            llTop.setVisibility(View.GONE);
        }


        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 1))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.hang_1c1))
        );
        slimAdapter = SlimAdapter.create().register(R.layout.app_recy_item_coin, new SlimInjector<CoinBean>() {
            @Override
            public void onInject(CoinBean data, IViewInjector injector, List payloads) {

                injector
                        .background(R.id.viewCoin, ContextCompat.getDrawable(App.INSTANCE, CoinEnum.getByCode(data.getCode().replace("_", "/").toUpperCase().split("/")[0]).getRes()))
//                        .imageCircle(R.id.viewCoin, coinMap.get(data.getCode()))
                        .text(R.id.tvUSDT, data.getPrice())
                        .text(R.id.tvType, "/"+data.getRCode())
                        .text(R.id.tvRMB, "≈ ¥ " + CoinUtil.keepRMB(data.getCnyPrice()))
                        .text(R.id.tvCode, data.getLCode())
                        .text(R.id.tvRate, data.getChangeRate().charAt(0) == '-' ? data.getChangeRate() : ("+" + data.getChangeRate()))
                        .background(R.id.tvRate, ContextCompat.getDrawable(App.INSTANCE, data.isUp() ? R.drawable.app_shape_corner35_03c : R.drawable.app_shape_corner35_ff5))
//                        .textColor(R.id.tvRate, ContextCompat.getColor(App.INSTANCE, data.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()))
                        .textColor(R.id.tvUSDT, ContextCompat.getColor(App.INSTANCE, data.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor()))
//                        .textColor(R.id.tvUSDT, data.getLight() ?
//                                (getResources().getColor(data.isUp() ? ColorEnum.UP.getColor() : ColorEnum.DOWN.getColor())) :
//                                getResources().getColor(R.color.hang_b2b))
                ;
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());

        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView1, position, v) -> {
                    if (!isSlide) {
                        ARouter.getInstance().build(RConfig.APP_MARKET)
                                .withString(Constans.CODE, ((CoinBean) slimAdapter.getDataItem(position)).getCode())
                                .withString(Constans.QU, qu)
                                .navigation();
                    } else {
                        RxBus.getDefault().post(new CoinType(((CoinBean) slimAdapter.getDataItem(position)).getCode()));
                        getActivity().finish();
                    }
                });
        ClickUtil.click(tvUSDT, () -> {
            qu = "USDT";
            mPresenter.getProduct(qu);
            tvUSDT.setTextColor(getResources().getColor(R.color.hang_b2b));
            tvBTC.setTextColor(getResources().getColor(R.color.commonWhite));
            tvETH.setTextColor(getResources().getColor(R.color.commonWhite));
        });
        ClickUtil.click(tvBTC, () -> {
            qu = "BTC";
            mPresenter.getProduct(qu);
            tvUSDT.setTextColor(getResources().getColor(R.color.commonWhite));
            tvBTC.setTextColor(getResources().getColor(R.color.hang_b2b));
            tvETH.setTextColor(getResources().getColor(R.color.commonWhite));
        });
        ClickUtil.click(tvETH, () -> {
            qu = "ETH";
            mPresenter.getProduct(qu);
            tvUSDT.setTextColor(getResources().getColor(R.color.commonWhite));
            tvBTC.setTextColor(getResources().getColor(R.color.commonWhite));
            tvETH.setTextColor(getResources().getColor(R.color.hang_b2b));
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(List<CoinBean> data) {
        if (slimAdapter == null || data == null || data.size() == 0)
            return;
        coinMap = new HashMap<>();
        Flowable.fromIterable(data)
                .filter(coinBean -> coinBean.getCode() != null)
                .toList()
                .subscribe(coinBeans -> {
                    slimAdapter.updateData(coinBeans);
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshCoin(CoinBean stockSocketBean) {
        if (slimAdapter == null || slimAdapter.getData() == null || slimAdapter.getData().size() == 0)
            return;

        if (slimAdapter != null) {
            Flowable.fromIterable(slimAdapter.getData())
                    .filter(item -> item.getCode().equals(stockSocketBean.getCode()))
                    .subscribe(item -> {
                        stockSocketBean.setLight(true);
                        stockSocketBean.setImg(item.getImg());
                        int position = slimAdapter.getData().indexOf(item);
                        slimAdapter.getData().set(position, stockSocketBean);
                        slimAdapter.notifyItemChanged(position, 1);
                        DisposUtil.close(timeMap.get(item.getCode()));
                        Disposable subscribe = Flowable.timer(1000, TimeUnit.MILLISECONDS)
                                .subscribeOn(Schedulers.newThread())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(i -> {
                                    stockSocketBean.setLight(false);
                                    slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(stockSocketBean), 1);
                                });
                        timeMap.put(item.getCode(), subscribe);
                    }, e -> {
                    });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, code = RxBusCode.REFRESH_HANGQING)
    public void refresh() {
        if (mPresenter != null) {
            mPresenter.getProduct(qu);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeQu(QuBean quBean) {
        qu = quBean.getQu();
        if (mPresenter != null) {
            mPresenter.getProduct(quBean.getQu());
        }
    }

    @Override
    public void initData() {
        mPresenter.getProduct(qu);
    }

}
